package com.youshang.config;

import com.youshang.model.MaskModel;
import org.springframework.util.StringUtils;

/**
 * 两个工具类方法是 copy Hu tool的工具方法
 */
public enum DataMaskingFunc {

     /**
     *  脱敏转换器
     */
     NO_MASK((str, maskModel) -> str),
     ALL_MASK((str, maskChar) -> wrapperMask(str,maskChar));

    private final DataMaskingOperation operation;

    private DataMaskingFunc(DataMaskingOperation operation) {
        this.operation = operation;
    }

    public DataMaskingOperation operation() {
        return this.operation;
    }

    /**
     * 假设：123456789
     * markChar = *
     * position = 2
     * offset = 4
     * 结果为：12**56789
     * @param content
     * @param maskModel
     * @return
     */
    private static String  wrapperMask(String content, MaskModel maskModel){
        if (StringUtils.hasLength(content)) {
            return replace(content, maskModel.getPosition(), maskModel.getOffset(), maskModel.getMarkChar());
        } else {
            return content;
        }
    }
    /**
     * 替换指定字符串的指定区间内字符为固定字符
     *
     * @param str 字符串
     * @param startInclude 开始位置（包含）
     * @param endExclude 结束位置（不包含）
     * @param replacedChar 被替换的字符
     * @return 替换后的字符串
     * @since 3.2.1
     */
    public static String replace(CharSequence str, int startInclude, int endExclude, char replacedChar) {
        if (null == str || "".equals(str)) {
            return str(str);
        }
        if (startInclude == 0 && endExclude == 0) {
            return replace(str,0,str.length(),replacedChar);
        }
        final int strLength = str.length();
        if (startInclude > strLength) {
            return str(str);
        }
        if (endExclude > strLength) {
            endExclude = strLength;
        }
        if (startInclude > endExclude) {
            // 如果起始位置大于结束位置，不替换
            return str(str);
        }

        final char[] chars = new char[strLength];
        for (int i = 0; i < strLength; i++) {
            if (i >= startInclude && i < endExclude) {
                chars[i] = replacedChar;
            } else {
                chars[i] = str.charAt(i);
            }
        }
        return new String(chars);
    }

    /**
     * {@link CharSequence} 转为字符串，null安全
     *
     * @param cs {@link CharSequence}
     * @return 字符串
     */
    public static String str(CharSequence cs) {
        return null == cs ? null : cs.toString();
    }

}